/*
 * @Author: Choisaaaa
 * @Date: 2018/5/5  0:41
 * 商品种类添加 组件
 */

import React from "react";

import Footer from "component/footer/footer.jsx";
import PageTitle from 'component/page-title/page-title.jsx';
import ProductCategory from 'service/product-category-service.jsx'
import FileUploader from 'util/file-uploader/index.jsx';    //图片上传子组件
import MUtil from 'util/mm.jsx';

const _category = new ProductCategory();
const _mm = new MUtil();

class CategoryAdd extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            categoryList : [],      //商品品类列表
            parentCategoryId :  0,  //品类的父级ID
            categoryName : "",       //品类名称
            subImages : []

        }
    }
    componentDidMount(){
        this.loadCategoryList();
    }
    componentWillMount(){//组件将要加载
        this.mounted = true;
    }
    componentWillUnmount(){//组件销毁
        this.mounted = false;
    }
    loadCategoryList(){//加载商品种类列表
        _category.getCategoryList().then((res) => {
            if(this.mounted){
                this.setState({
                    categoryList : res
                });
            }
        },(errMsg)=>{
            _mm.errorTips(errMsg)
        });
    }
    onValueChange(e){//监听输入框和下拉框的值的改变
        let name = e.target.name,
            value = e.target.value;
       this.setState({
           [name] : value
       });
    }
    onSubmit(){//提交按钮的事件
        let categoryName = this.state.categoryName.trim(),
            imageAdress = this.state.subImages[0];
        if(categoryName && imageAdress){
            _category.saveCategory({
                parentId  : this.state.parentCategoryId,
                categoryName : categoryName,
                imageAddress : this.getSubImagesString()
            }).then((res) =>{
                _mm.successTips(res);
                this.props.history.push('/product-category/index');//跳转到商品种类的首页
            },(errMsg) =>{
                _mm.errorTips(errMsg)
            });
        }else{
            _mm.errorTips("名称和图片不能为空");
            return;
        }
    }
    onUploadSuccess(res){//方法3.图片上传成功，将服务响应回来的图片地址保存到数组中
        let subImages = this.state.subImages;
        var image = {
            url : res[0].url,
            uri : res[0].uri
        }
        subImages.push(image);
        this.setState({
            subImages : subImages
        });
    }
    onUploadError(errMsg){//方法4.图片上传失败
        _mm.errorTips(errMsg)
    }
    onImageDelete(e){//方法5.删除上传的图片
        let index = e.target.getAttribute("index");
        let subImages = this.state.subImages;
        subImages.splice(index,1);
        this.setState({
            subImages : subImages
        });
    }
    getSubImagesString (){//将数据元素拼接成String返回
        return this.state.subImages.map((image) =>image.uri).join(",");
    }
    render(){
        let blankDivCss = {//使用一个空白的div撑开与footer之间的距离
            height : "90px"
        } ;
        return(
            <div id="page-wrapper">

                <PageTitle title="新增品类"/>
                <div className="row">
                    <div className="col-md-12">
                        <div className="form-horizontal">
                            <div className="form-group">
                                <label className="col-md-2 control-label">所属品类</label>
                                <div className="col-md-5">
                                    <select name="parentCategoryId"
                                            className="form-control"
                                            onChange={(e) => this.onValueChange(e)}>
                                        <option value="0">根品类/</option>
                                        {
                                            this.state.categoryList.map((category, index) => {
                                                return <option value={category.id} key={index}>根品类/{category.productCategoryName}</option>
                                            })
                                        }
                                    </select>
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-md-2 control-label">品类名称</label>
                                <div className="col-md-5">
                                    <input type="text" className="form-control"
                                           placeholder="请输入品类名称"
                                           name="categoryName"
                                           value={this.state.name}
                                           onChange={(e) => this.onValueChange(e)}/>
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-md-2 control-label">品类图片</label>
                                <div className="col-md-10">
                                    {
                                        this.state.subImages.length
                                            ? this.state.subImages.map((image,index) =>
                                            (<div className="img-con" key={index}>
                                                <img src={image.url} alt="商品图片" className="img" id={image.host}/>
                                                <i className="fa fa-close" index={index} onClick={(e) => this.onImageDelete(e)} />
                                            </div>)
                                        )  : (<div className="choose-img">请上传图片</div>)
                                    }
                                </div>
                                <div className="col-md-offset-2 col-md-10 file-upload-con">
                                    <FileUploader onSuccess={(res)=>this.onUploadSuccess(res)}
                                                  onError={(errMsg) => this.onUploadError(errMsg)}
                                                  maxFiles = "1"
                                                  fileFieldName = "category"
                                    />
                                </div>
                            </div>
                            <div className="form-group">
                                <div className="col-md-offset-2 col-md-10">
                                    <button type="submit" className="btn btn-primary"
                                            onClick={(e) => {this.onSubmit(e)}}><i className="fa fa-paper-plane"/> Submit</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="row" style={blankDivCss}></div>
                <Footer/>
            </div>
        );
    }
}
export default CategoryAdd;